from World import ItemRegistry


class Slot:
    def __init__(self, item_id=-1, item_amount=0):
        self.item_id = item_id
        self.item_amount = item_amount


class PlayerInventory:
    def __init__(self, inventory_size=9, save_manager=None):
        self.inventory_size = inventory_size
        self.save_manager = save_manager
        self.selected_slot = 0

        inventory_data = None if save_manager is None else self.load()
        if inventory_data is not None:
            self.inventory = inventory_data
        else:
            self.inventory = [Slot(), Slot(), Slot(), Slot(), Slot(), Slot(), Slot(), Slot(), Slot()]

    def has_item(self, item_id):
        for i in range(0, self.inventory_size):
            if self.inventory[i].item_id == item_id:
                return True, i
        return False, -1

    def add_item(self, item_id, amount=1):
        if item_id not in ItemRegistry:
            return False
        has_item = self.has_item(item_id)
        if has_item[0]:
            self.inventory[has_item[1]].item_amount += amount
            return True
        else:
            for i in range(0, self.inventory_size):
                if self.inventory[i].item_id == -1:
                    self.inventory[i].item_id = item_id
                    self.inventory[i].item_amount = amount
                    return True

    def remove_item(self, item_id, amount=1):
        for i in range(0, self.inventory_size):
            if self.inventory[i].item_id == item_id:
                self.inventory[i].item_amount -= amount
                if self.inventory[i].item_amount <= 0:
                    self.inventory[i].item_id = -1
                    self.inventory[i].item_amount = 0
                break
    def set_item(self, item_id, amount, slot_index):
        self.inventory[slot_index].item_id = item_id
        self.inventory[slot_index].item_amount = amount

    def clear_all_items(self):
        for i in range(0, self.inventory_size):
            self.inventory[i].item_id = -1
            self.inventory[i].item_amount = 0

    def show(self):
        for i in range(0, self.inventory_size):
            print(f"Slot {i} : Item id : {self.inventory[i].item_id}, item amount : {self.inventory[i].item_amount}")

    def save(self):
        self.save_manager.save_inventory_data(self.inventory)

    def load(self):
        return self.save_manager.load_inventory_data()
